<template>
  <view>
    <view class="deviceList">
      <view class="left_right_control">
        <view class="left-home">
          <uni-data-select
            class="store-select"
            v-model:value="storeId"
            :localdata="range"
            @change="change"
            :clear="false"
          ></uni-data-select>
        </view>
        <view
          class="gd-list-btn"
          style="margin: auto 20rpx"
        >
          <button
            :type="allCkeck ? 'warn' : 'primary'"
            size="mini"
            @click="checkedAll"
          >
            {{ allCkeck ? '全不选' : '全选' }}
          </button>
        </view>
      </view>
      <view
        class="scroll-list"
        scroll-y="true"
        :style="'height:' + clientHeight + 'px;'"
      >
        <checkbox-group @change="checkboxChange">
          <view
            v-if="deviceList.length > 0"
            class="base-list"
          >
            <view
              v-for="(item, index) in deviceList"
              :key="index"
            >
              <view
                :class="
                  (index + 1) % 2 !== 0
                    ? 'base-item base-item-left'
                    : 'base-item'
                "
              >
                <view class="divece-all">
                  <view class="isline">
                    <checkbox
                      :value="
                        JSON.stringify({
                          equipmentNo: item.equipmentNo,
                          equipmentTypeId: item.equipmentTypeId,
                        })
                      "
                      :checked="item.checked"
                    ></checkbox>
                  </view>
                  <view class="divece-right">
                    <view class="base-icon">
                      <image
                        class="base-icon-images"
                        src="https://mkservice.mk-iot.com/subFile/mk2240/device.png"
                        mode="aspectFit"
                      />
                    </view>
                  </view>
                  <view class="divece-left">
                    <view class="base-name">{{ item.equipmentName }}</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </checkbox-group>
        <view
          class="no-devicelist"
          v-if="deviceList.length <= 0"
        >
          <image
            src="https://mkservice.mk-iot.com/subFile/mk2240/no-device.png"
            alt=""
          />
          <text>暂无设备</text>
        </view>
      </view>
      <view class="remove_device">
        <button
          type="warn"
          @tap="imgUpload"
          style="
            width: 80%;
            background-color: #ff976a;
            height: 80rpx;
            line-height: 80rpx;
            margin-top: 20rpx;
          "
        >
          图片上传
        </button>
      </view>
      <uni-popup
        ref="popup"
        background-color="#fff"
        :show="show"
        @change="popupchange"
      >
        <view class="popup-content">
          <view class="picture">
            <view class="left"> 图片: </view>
            <view class="right">
              <view
                class="feedback-image-item"
                v-for="(item, index) in pics"
                :key="index"
              >
                <view
                  class="close-icon"
                  v-if="!isdisabled"
                  @tap="delImg(index)"
                >
                  <uni-icons
                    type="closeempty"
                    size="18"
                    color="#fff"
                  ></uni-icons>
                </view>
                <view class="image-box">
                  <image
                    :src="item.url"
                    mode="aspectFill"
                    @tap="previewImg(item.url)"
                  ></image>
                </view>
              </view>

              <view
                v-if="pics.length < 1 && !isdisabled"
                class="feedback-image-item"
                @tap="addImage"
              >
                <view class="image-box">
                  <uni-icons
                    type="plusempty"
                    size="50"
                    color="#c7c7c7"
                  ></uni-icons>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="btn_item">
          <button
            type="warn"
            @tap="onclose"
            size="mini"
          >
            关闭
          </button>
          <button
            @tap="submitImg"
            type="primary"
            size="mini"
          >
            提交
          </button>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script>
  import { myStoreAndShareList } from '@/api/system/store/store.js'
  import {
    delEquipment,
    deviceImgUploadAdd,
  } from '@/api/system/equiment/equipment.js'
  export default {
    data() {
      return {
        //是否有弹框
        show: false,
        isdisabled: false,
        clientHeight: 0,
        userId: uni.getStorageSync('userId'),
        deviceList: [],
        range: [],
        checkedList: [],
        storeId: null,
        allCkeck: false,
        queryParams: {
          userId: null,
        },
        isAdmin: false,
        pics: [],
      }
    },
    onShow() {
      var that = this
      uni.getSystemInfo({
        success: function (res) {
          let screenHeight = uni.getSystemInfoSync().windowHeight //获取屏幕高度
          // 通过query 获取其余盒子的高度
          let query = uni.createSelectorQuery().in(that)
          query.select('.left_right_control').boundingClientRect()
          query.select('.remove_device').boundingClientRect()
          //通过query.exec返回的数组 进行减法 同时 去除margin 和border的
          query.exec((res) => {
            let h1 = res[0].height
            let h2 = res[1].height
            let scrollHeight = screenHeight - h1 - h2 - 20
            that.clientHeight = scrollHeight
          })
        },
      })
    },
    onLoad(option) {
      this.storeId = option.storeId != 'null' ? parseInt(option.storeId) : null
      //查询当前门店
      this.getStoreList()
    },
    methods: {
      //弹窗时出现滑动穿透解决方案
      popupchange(e) {
        this.show = e.show
      },
      onclose() {
        // TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
        this.$refs.popup.close()
      },
      //查询门店列表
      getStoreList() {
        this.$modal.loading('数据加载中...')
        this.queryParams.userId = this.userId
        //查询个人的门店和查询已经接受分享的门店
        myStoreAndShareList(this.queryParams).then((response) => {
          if (response.code == 200) {
            // 关闭遮罩层
            this.$modal.closeLoading()
            uni.stopPullDownRefresh()
            this.storeList = response.rows
            //获取数据后
            this.range = response.rows.map((x) => ({
              value: parseInt(x.storeId),
              text: x.storeName,
            }))
            //默认第一个门店
            if (this.storeId == null) {
              this.storeId = this.range[0].value
              //默认显示第一个门店的设备
              this.deviceList = response.rows[0].mkEquipments
              this.isAdmin = response.rows[0].isAdmin == '1' ? true : false
            } else {
              this.getDeviceList()
            }
          }
        })
      },
      //新增图片
      addImage() {
        // const count = 5 - this.pics.length
        const count = 1
        uni.chooseImage({
          count: count, // 最多可以选择的图片张数，默认9
          sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
          sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
          success: (res) => {
            const tempFilePaths = res.tempFilePaths
            tempFilePaths.forEach((item, index) => {
              if (index < count) {
                //处理小程序多选状况
                this.pics.push({
                  url: item,
                })
              }
            })
          },
        })
      },
      //点击上传图片
      submitImg() {
        if (this.pics.length > 0) {
          this.checkedList.forEach((item) => {
            //设备id，图片名称，路径
            let data = {
              equipmentNo: item.equipmentNo,
              equipmentTypeId: item.equipmentTypeId,
              name: 'deviceImg',
              filePath: this.pics[0].url,
            }
            //保存到数据库的方法调用
            deviceImgUploadAdd(data).then((response) => {
              if (response.code == 200) {
                this.pics = []
                this.$refs.popup.close()
                this.checkedList = []
                this.getStoreList()
                this.$modal.msgSuccess('上传成功')
              } else {
                this.$modal.msgError('上传失败')
              }
            })
          })
        } else {
          this.$modal.msgError('请选择上传的图片')
        }
      },
      //删除图片
      delImg(index) {
        this.pics.splice(index, 1)
      },
      //浏览图片
      previewImg(url) {
        uni.previewImage({
          urls: [url],
        })
      },
      //切换门店方法
      change(e) {
        this.storeId = e
        this.radioValue = null
        this.getDeviceList()
      },
      //查询设备分列表公共方法
      getDeviceList() {
        //查询设备列表
        this.storeList.map((item, index) => {
          if (item.storeId == this.storeId) {
            this.storeName = item.storeName
            this.deviceList = item.mkEquipments
            this.isAdmin = item.isAdmin == '1' ? true : false
          }
        })
      },
      //自定义多选按钮的点击方法
      checkboxChange(e) {
        this.checkedList = e.detail.value
        //将数组的对象string的json格式转换为对象的JSON格式
        this.checkedList = this.checkedList.map((item) => JSON.parse(item))
        if (e.detail.value.length === this.deviceList.length) {
          this.allCkeck = true
        } else {
          this.allCkeck = false
        }
        //两个数组循环，判断是否勾选了，如果勾选给设备数组赋值checked:true
        this.deviceList.forEach((k, i) => {
          const ispresent = this.checkedList.find(
            (p, j) => p.equipmentNo == k.equipmentNo
          )
          if (ispresent) {
            this.$set(this.deviceList[i], 'checked', true)
          } else {
            this.$set(this.deviceList[i], 'checked', false)
          }
        })
      },
      // 全选
      checkedAll() {
        this.checkedList = []
        let items = this.deviceList
        if (!this.allCkeck) {
          this.allCkeck = true
          this.deviceList.forEach((item, index) => {
            this.$set(this.deviceList[index], 'checked', true)
            if (!this.deviceList[index].checked) {
              this.$set(this.deviceList[index], 'checked', true)
            }
            this.checkedList.push({
              equipmentNo: this.deviceList[index].equipmentNo,
              equipmentTypeId: this.deviceList[index].equipmentTypeId,
            })
          })
        } else {
          this.allCkeck = false
          this.checkedList = []
          this.deviceList.forEach((item, index) => {
            this.$set(this.deviceList[index], 'checked', false)
          })
        }
      },
      //图片上传
      imgUpload() {
        if (this.checkedList.length > 0) {
          this.$refs.popup.open()
        } else {
          this.$modal.msgError('请选择设备')
        }
      },
    },
    //下拉刷新
    onPullDownRefresh() {
      this.checkedList = []
      this.getStoreList()
    },
  }
</script>

<style lang="scss">
  page {
    background-color: #f6f6f6;
  }

  .scroll-list {
    width: auto;
    height: 100%;
    overflow: scroll;
  }

  .base-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 10px 10px 0 10px;
  }

  .no-devicelist {
    display: flex;
    flex-direction: column;
    text-align: center;
    align-items: center;
    justify-content: center;
    font-size: 36rpx;
  }

  .no-devicelist > image {
    margin-top: 200rpx;
    width: 200rpx;
    height: 200rpx;
  }

  .no-devicelist > text {
    margin-top: 20rpx;
  }

  .base-item {
    background-color: #ffffff;
    margin-bottom: 12px;
    width: 346rpx;
    height: 278rpx;
    border-radius: 10px;
    display: flex;
    align-items: center;
    // box-shadow: 0px 0px 3px 3px rgba(170, 168, 168, 0.5)
  }

  .base-icon {
    width: 140rpx;
    height: 160rpx;
  }

  .base-icon-images {
    width: 100%;
    height: 100%;
  }

  .left_right_control {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .left-home {
    margin-left: 30rpx;
    width: 300rpx;
  }

  ::v-deep .store-select .uni-select {
    font-size: 32rpx;
    color: #323232;
    font-weight: bold;
    border: 1px solid #f6f6f6;
    border-bottom: solid 1px #f6f6f6;
  }

  // 按钮
  .right-add {
    align-items: center;
    display: flex;
  }

  .right-add-img {
    width: 34rpx;
    height: 34rpx;
    margin: auto 18rpx;
  }

  .right-add-text {
    margin-right: 28rpx;
    font-size: 32rpx;
    color: #323232;
    font-weight: bold;
  }
  // 图片
  .img-barnner {
    width: 100%;
    text-align: center;
    margin-top: 50rpx;
  }
  // 轮播
  .img-barnner > image {
    width: 670rpx;
    height: 260rpx;
  }
  // 设备的
  .divice-list {
    margin-top: 33rpx;
  }

  .divice-tabs {
    display: flex;
    align-items: center;
  }

  .device-text {
    font-size: 28rpx;
    color: #323232;
    font-weight: bold;
    margin: auto 20rpx;
  }

  .divece-tab {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    width: 75%;
    flex-direction: row;
    align-items: center;
    overflow: visible;
    white-space: nowrap;
  }
  // 滚动的
  .scroll-view_H {
    width: 100%;
    overflow: scroll;
  }

  .divece-all {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
    flex-direction: column;
  }

  .divece-left {
    margin-top: 5rpx;
  }

  .base-name {
    font-size: 32rpx;
    color: #323232;
    font-weight: bold;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  // 产品名称
  .product-name {
    font-size: 28rpx;
    color: #979797;
    margin-top: 30rpx;
  }

  .isline {
    margin-left: 240rpx;
  }

  .remove_device {
    text-align: center;
    margin-bottom: 20rpx;
  }

  .removeDevice {
    width: 80%;
  }

  .popup-content {
    width: 350px;
  }

  .picture {
    width: 100%;
    overflow: hidden;
    background: #fff;
  }

  .picture .left {
    width: 100rpx;
    font-size: 30rpx;
    float: left;
    padding-left: 30rpx;
    padding-top: 20rpx;
  }

  .picture .right {
    width: 610rpx;
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx;

    .feedback-image-item {
      position: relative;
      width: 33.33%;
      height: 0;
      padding-top: 33.33%;
      box-sizing: border-box;

      .close-icon {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 0;
        right: 0;
        width: 44rpx;
        height: 44rpx;
        border-radius: 50%;
        background-color: #ff5a5f;
        z-index: 2;
      }

      .image-box {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 10rpx;
        right: 10rpx;
        left: 10rpx;
        bottom: 10rpx;
        border: 1px #c7c7c7 solid;
        border-radius: 10rpx;
        overflow: hidden;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .btn_item {
    display: flex;
    margin: 20rpx 0;
  }
</style>
